import 'package:flutter/material.dart';
import 'package:flutter_hex_color/flutter_hex_color.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:signage/app/data/models/member_info_item_model.dart';
import 'package:signage/app/data/models/member_group_model.dart';
import 'package:signage/app/data/models/template_model.dart';
import 'package:signage/app/utils/toast_utils.dart';
import 'dart:math';

import 'package:signage/app/widgets/board_widget.dart';
import 'package:signage/l10n/l10n.dart';

class AddMemberDialog extends StatefulWidget {
  final Function(MemberItem) onMemberAdded;
  final TemplateModel? templateModelA;
  final TemplateModel? templateModelB;
  final int? sampleValue;
  final MemberItem? member;

  const AddMemberDialog({
    Key? key,
    required this.onMemberAdded,
    required this.templateModelA,
    required this.templateModelB,
    required this.sampleValue,
    this.member,
  }) : super(key: key);

  @override
  State<AddMemberDialog> createState() => _AddMemberDialogState();
}

class _AddMemberDialogState extends State<AddMemberDialog> {
  late List<MemberInfoItem> memberInfoListA;
  late List<MemberInfoItem> memberInfoListB;
  final Map<String, TextEditingController> controllers = {};
  final ScrollController _scrollController = ScrollController();
  int tabIndex = 0;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _initData();
  }

  void _initData() {
    widget.templateModelA?.elements.where((e) => e['type'] == 'text').toList();
    memberInfoListA = (widget.templateModelA?.memberInfos ?? [])
        .map((e) =>
            MemberInfoItem(keyName: e.keyName, value: e.value, type: 'A'))
        .toList();
    memberInfoListB = (widget.templateModelB?.memberInfos ?? [])
        .map((e) =>
            MemberInfoItem(keyName: e.keyName, value: e.value, type: 'B'))
        .toList();

    if (widget.member != null) {
      if (widget.sampleValue == 0) {
        memberInfoListA = widget.member?.memberInfoList ?? [];
      } else {
        memberInfoListA = [];
        memberInfoListB = [];
        widget.member!.valueAList.forEach((e) {
          memberInfoListA.add(MemberInfoItem(keyName: e, value: e, type: 'A'));
        });
        widget.member!.valueBList.forEach((e) {
          memberInfoListB.add(MemberInfoItem(keyName: e, value: e, type: 'B'));
        });
      }
    }
    print(
        "初始化 A面信息列表: ${memberInfoListA.map((e) => '${e.keyName}: ${e.value}  ${e.type}').toList()}");
    print(
        "初始化 B面信息列表: ${memberInfoListB.map((e) => '${e.keyName}: ${e.value}  ${e.type}').toList()}");
    print("初始化完成 sampleValue ${widget.sampleValue}");
    switch (widget.sampleValue) {
      case 0:
        tabIndex = 0;
        break;
      case 1:
        tabIndex = 0;
        break;
      case 2:
        tabIndex = 0;
        break;
      case 3:
        tabIndex = 1;
        break;
    }
    // 初始化控制器
    _initControllers();
  }

  void _initControllers() {
    // 清理旧的控制器
    controllers.forEach((_, controller) => controller.dispose());
    controllers.clear();

    // 初始化A面控制器
    for (var item in memberInfoListA) {
      final controllerKey = 'A_${item.keyName}';
      controllers[controllerKey] = TextEditingController(text: item.value);
      print("创建A面控制器: $controllerKey, 初始值: ${item.value}");
    }

    // 只在AB面不同时初始化B面控制器
    if (widget.sampleValue != 0) {
      for (var item in memberInfoListB) {
        final controllerKey = 'B_${item.keyName}';
        controllers[controllerKey] = TextEditingController(text: item.value);
        print("创建B面控制器: $controllerKey, 初始值: ${item.value}");
      }
    }

    if (widget.templateModelA == null && widget.templateModelB == null) {
      addNewField('A');
    }
  }

  void addNewField(String type) {
    setState(() {
      switch (widget.sampleValue) {
        case 0:
          final newKey = AppLocalizations.of(context)!.translate('info', params: {'index': (memberInfoListA.length + 1).toString()});
          memberInfoListA
              .add(MemberInfoItem(keyName: newKey, value: '', type: 'AB'));
          final controllerKey = 'A_$newKey';
          var controller = TextEditingController();
          controllers[controllerKey] = controller;
          print("添加新字段: $newKey, controllerKey: $controllerKey");
          break;
        case 1:
          if (type == 'A') {
            final newKey = AppLocalizations.of(context)!.translate('info', params: {'index': (memberInfoListA.length + 1).toString()});
            memberInfoListA
                .add(MemberInfoItem(keyName: newKey, value: '', type: 'A'));
            final controllerKey = 'A_$newKey';
            var controller = TextEditingController();
            controllers[controllerKey] = controller;
            print("添加新字段: $newKey, controllerKey: $controllerKey");
          } else {
            final newKey = AppLocalizations.of(context)!.translate('info', params: {'index': (memberInfoListB.length + 1).toString()});
            memberInfoListB
                .add(MemberInfoItem(keyName: newKey, value: '', type: 'B'));
            final controllerKey = 'B_$newKey';
            var controller = TextEditingController();
            controllers[controllerKey] = controller;
            print("添加新字段: $newKey, controllerKey: $controllerKey");
          }
          break;
        case 2:
          final newKey = AppLocalizations.of(context)!.translate('info', params: {'index': (memberInfoListA.length + 1).toString()});
          memberInfoListA
              .add(MemberInfoItem(keyName: newKey, value: '', type: 'A'));
          final controllerKey = 'A_$newKey';
          var controller = TextEditingController();
          controllers[controllerKey] = controller;
          print("添加新字段: $newKey, controllerKey: $controllerKey");
          break;
        case 3:
          final newKey = AppLocalizations.of(context)!.translate('info', params: {'index': (memberInfoListB.length + 1).toString()});
          memberInfoListB
              .add(MemberInfoItem(keyName: newKey, value: '', type: 'B'));
          final controllerKey = 'B_$newKey';
          var controller = TextEditingController();
          controllers[controllerKey] = controller;
          print("添加新字段: $newKey, controllerKey: $controllerKey");
          break;
      }
    });

    if (_scrollController.hasClients) {
      _scrollController.animateTo(
        _scrollController.position.maxScrollExtent + 40.h,
        duration: const Duration(milliseconds: 100),
        curve: Curves.easeOut,
      );
    }
  }

  // A面输入框部分
  Widget _buildASideInputs() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        ...memberInfoListA.asMap().entries.map((entry) {
          final index = entry.key;
          final item = entry.value;
          final controllerKey = 'A_${item.keyName}';
          print(
              "渲染A面输入框 $index: ${item.keyName}, type: ${item.type}, 当前值: ${item.value}");

          return Padding(
            padding: const EdgeInsets.symmetric(vertical: 8.0),
            child: Row(
              children: [
                Expanded(
                  flex: 2,
                  child: Text(item.keyName ?? ''),
                ),
                Expanded(
                  flex: 5,
                  child: TextField(
                    controller: controllers[controllerKey],
                    decoration: InputDecoration(
                      isDense: true,
                      hintText: AppLocalizations.of(context)!.translate('enter_field', params: {'field': item.keyName ?? ''}),
                      fillColor: Color.fromRGBO(243, 244, 246, 1),
                      filled: true,
                      border: InputBorder.none,
                      contentPadding:
                          EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                    ),
                    onChanged: (value) {
                      setState(() {
                        memberInfoListA[index].value = value;
                      });
                    },
                  ),
                ),
                16.horizontalSpace,
                GestureDetector(
                  onTap: () {
                    setState(() {
                      if (memberInfoListA.length > 1) {
                        memberInfoListA.removeAt(index);
                      } else {
                        ToastUtils.show(AppLocalizations.of(context)!.translate('please_keep_one_field'));
                      }
                    });
                  },
                  child: Image.asset(
                    'assets/images/Group 1321318584@2x.png',
                    width: 24.w,
                    height: 24.w,
                  ),
                )
              ],
            ),
          );
        }).toList(),
      ],
    );
  }

  // B面输入框部分
  Widget _buildBSideInputs() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        ...memberInfoListB.asMap().entries.map((entry) {
          final index = entry.key;
          final item = entry.value;
          final controllerKey = 'B_${item.keyName}';
          print(
              "渲染B面输入框 $index: ${item.keyName}, type: ${item.type}, 当前值: ${item.value}");

          return Padding(
            padding: const EdgeInsets.symmetric(vertical: 8.0),
            child: Row(
              children: [
                Expanded(
                  flex: 2,
                  child: Text(item.keyName ?? ''),
                ),
                Expanded(
                  flex: 5,
                  child: TextField(
                    controller: controllers[controllerKey],
                    decoration: InputDecoration(
                      isDense: true,
                      hintText: AppLocalizations.of(context)!.translate('enter_field', params: {'field': item.keyName ?? ''}),
                      fillColor: Color.fromRGBO(243, 244, 246, 1),
                      filled: true,
                      border: InputBorder.none,
                      contentPadding:
                          EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                    ),
                    onChanged: (value) {
                      setState(() {
                        memberInfoListB[index].value = value;
                      });
                    },
                  ),
                ),
                16.horizontalSpace,
                GestureDetector(
                  onTap: () {
                    setState(() {
                      if (memberInfoListB.length > 1) {
                        memberInfoListB.removeAt(index);
                      } else {
                          ToastUtils.show(AppLocalizations.of(context)!.translate('please_keep_one_field'));
                      }
                    });
                  },
                  child: Image.asset( 
                    'assets/images/Group 1321318584@2x.png',
                    width: 24.w,
                    height: 24.w,
                  ),
                ),
              ],
            ),
          );
        }).toList(),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    final bool isSameSides = widget.sampleValue == 0;
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(10.w),
          topRight: Radius.circular(10.w),
        ),
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 标题
          Padding(
            padding: EdgeInsets.all(16.w),
            child: Row(
              children: [
                GestureDetector(
                  onTap: () {
                    Navigator.pop(context);
                  },
                  child: Text(
                    AppLocalizations.of(context)!.translate('cancel'),
                    style: TextStyle(
                      fontSize: 16.sp,
                      fontWeight: FontWeight.normal,
                      letterSpacing: 0,
                      color: Colors.black,
                    ),
                  ),
                ),
                Spacer(),
                Text(
                  AppLocalizations.of(context)!.translate('add_member'),
                  style: TextStyle(
                    fontSize: 16.sp,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                Spacer(),
                GestureDetector(
                  onTap: () {
                    // 检查所有显示的输入框是否都有值
                    bool hasEmptyFields = false;
                    String emptyFieldName = '';

                    print("验证A面输入框值:");
                    for (var item in memberInfoListA) {
                      final controllerKey = 'A_${item.keyName}';
                      final value =
                          controllers[controllerKey]?.text.trim() ?? '';
                      print(
                          "检查字段 ${item.keyName}: controllerKey=$controllerKey, value='$value'");

                      if (value.isEmpty) {
                        hasEmptyFields = true;
                        emptyFieldName = item.keyName ?? '';
                        print("发现空值字段: $emptyFieldName");
                        break;
                      }
                    }

                    // 如果A面验证通过且不是相同面板，继续检查B面输入框
                    if (!hasEmptyFields && widget.sampleValue != 0) {
                      print("验证B面输入框值:");
                      for (var item in memberInfoListB) {
                        final controllerKey = 'B_${item.keyName}';
                        final value =
                            controllers[controllerKey]?.text.trim() ?? '';
                        print(
                            "检查字段 ${item.keyName}: controllerKey=$controllerKey, value='$value'");

                        if (value.isEmpty) {
                          hasEmptyFields = true;
                          emptyFieldName = item.keyName ?? '';
                          print("发现B面空值字段: $emptyFieldName");
                          break;
                        }
                      }
                    }

                    if (hasEmptyFields) {
                      ToastUtils.show(AppLocalizations.of(context)!.translate('please_fill_field', 
                          params: {'field': emptyFieldName}));
                      return;
                    }

                    // 修改保存逻辑
                    List<MemberInfoItem> newMemberInfoList = [];

                    if (isSameSides) {
                      // AB面相同时，所有信息都标记为 type: 'AB'
                      for (var item in memberInfoListA) {
                        final value =
                            controllers['A_${item.keyName}']?.text.trim() ?? '';
                        newMemberInfoList.add(
                          MemberInfoItem(
                            keyName: item.keyName,
                            value: value,
                            type: 'AB', // 添加 type 字段
                          ),
                        );
                      }
                    } else {
                      // A面信息
                      for (var item in memberInfoListA) {
                        newMemberInfoList.add(
                          MemberInfoItem(
                            keyName: item.keyName,
                            value:
                                controllers['A_${item.keyName}']?.text.trim() ??
                                    '',
                            type: 'A', // 添加 type 字段
                          ),
                        );
                      }

                      // B面信息
                      for (var item in memberInfoListB) {
                        newMemberInfoList.add(
                          MemberInfoItem(
                            keyName: item.keyName,
                            value:
                                controllers['B_${item.keyName}']?.text.trim() ??
                                    '',
                            type: 'B', // 添加 type 字段
                          ),
                        );
                      }
                    }

                    final random = Random();
                    final uniqueId = DateTime.now().millisecondsSinceEpoch +
                        random.nextInt(10000);

                    MemberItem newMember = MemberItem(
                      id: uniqueId,
                      memberInfoList: newMemberInfoList,
                    );

                    widget.onMemberAdded(newMember);
                    Navigator.pop(context);
                  },
                  child: Container(
                    height: 28.w,
                    decoration: BoxDecoration(
                      color: Color(0xFFFCCF01),
                      borderRadius: BorderRadius.circular(4.w),
                    ),
                    child: Center(
                      child: Text(
                        AppLocalizations.of(context)!.translate('confirm'),
                        style: TextStyle(
                          fontSize: 14.sp,
                          color: Color(0xFF333333),
                        ),
                      ).paddingSymmetric(horizontal: 5.w),
                    ),
                  ),
                )
              ],
            ),
          ),

          if (widget.templateModelA != null || widget.templateModelB != null)
            SizedBox(
              height: 10.w,
            ),
          if (widget.templateModelA != null || widget.templateModelB != null)
            Container(
              margin: EdgeInsets.symmetric(horizontal: 94.w),
              height: 36.h,
              decoration: BoxDecoration(
                color: Colors.grey[100],
                borderRadius: BorderRadius.circular(18.r),
              ),
              child: Row(
                children: [
                  Expanded(
                    child: GestureDetector(
                      onTap: () => {
                        setState(() {
                          if (widget.sampleValue != 3) {
                            tabIndex = 0;
                          } else {
                            ToastUtils.show(AppLocalizations.of(context)!.translate('only_b_side_supported'));
                          }
                        }),
                      },
                      child: Container(
                        decoration: BoxDecoration(
                          color:
                              tabIndex == 0 ? Colors.white : Colors.transparent,
                          border: tabIndex == 0
                              ? Border.all(color: Colors.amber, width: 1)
                              : null,
                          borderRadius: BorderRadius.circular(18.r),
                          boxShadow: tabIndex == 0
                              ? [
                                  BoxShadow(
                                    color: Colors.black.withOpacity(0.1),
                                    blurRadius: 4,
                                    offset: Offset(0, 2),
                                  )
                                ]
                              : null,
                        ),
                        alignment: Alignment.center,
                        child: Text(
                          AppLocalizations.of(context)!.translate('side_a'),
                          style: TextStyle(
                            fontSize: 13.w,
                            color: tabIndex == 0
                                ? HexColor('#333333')
                                : HexColor('#999999'),
                            fontWeight: tabIndex == 0
                                ? FontWeight.w600
                                : FontWeight.normal,
                          ),
                        ),
                      ),
                    ),
                  ),
                  Expanded(
                    child: GestureDetector(
                      onTap: () => {
                        setState(() {
                          if (widget.sampleValue == 3 ||
                              widget.sampleValue == 1) {
                            tabIndex = 1;
                          } else {
                            ToastUtils.show(AppLocalizations.of(context)!.translate('only_ab_or_a_supported'));
                          }
                        }),
                      },
                      child: Container(
                        decoration: BoxDecoration(
                          color:
                              tabIndex == 1 ? Colors.white : Colors.transparent,
                          border: tabIndex == 1
                              ? Border.all(color: Colors.amber, width: 1)
                              : null,
                          borderRadius: BorderRadius.circular(18.r),
                          boxShadow: tabIndex == 1
                              ? [
                                  BoxShadow(
                                    color: Colors.black.withOpacity(0.1),
                                    blurRadius: 4,
                                    offset: Offset(0, 2),
                                  )
                                ]
                              : null,
                        ),
                        alignment: Alignment.center,
                        child: Text(
                          AppLocalizations.of(context)!.translate('side_b'),
                          style: TextStyle(
                            fontSize: 13.w,
                            color: tabIndex == 1
                                ? HexColor('#333333')
                                : HexColor('#999999'),
                            fontWeight: tabIndex == 1
                                ? FontWeight.w600
                                : FontWeight.normal,
                          ),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          10.verticalSpace,

          if (widget.templateModelA != null || widget.templateModelB != null)
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 16.w),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  // 预览区域
                  LayoutBuilder(
                    builder: (context, constraints) {
                      final previewWidth = (constraints.maxWidth - 32.w) / 2;
                      final aspectRatio = (widget.templateModelA?.width ??
                              widget.templateModelB?.width ??
                              800) /
                          (widget.templateModelA?.height ??
                              widget.templateModelB?.height ??
                              480);
                      final previewHeight = previewWidth / aspectRatio;

                      // 分别收集A面和B面的文本内容
                      List<String> previewTextsA = [];
                      List<String> previewTextsB = [];

                      // 收集A面的文本
                      for (var item in memberInfoListA) {
                        final value =
                            controllers['A_${item.keyName}']?.text.trim() ?? '';
                        if (value.isNotEmpty) {
                          previewTextsA.add(value);
                        }
                      }

                      // 收集B面的文本
                      for (var item in memberInfoListB) {
                        final value =
                            controllers['B_${item.keyName}']?.text.trim() ?? '';
                        if (value.isNotEmpty) {
                          previewTextsB.add(value);
                        }
                      }

                      print("预览文本 - A面: $previewTextsA");
                      print("预览文本 - B面: $previewTextsB");

                      return Row(
                        children: [
                          // A面预览
                          if (widget.sampleValue != 3 &&
                              widget.templateModelA != null)
                            Expanded(
                              child: Container(
                                width: previewWidth,
                                height: previewHeight,
                                child: BoardWidget(
                                  boardKey: GlobalKey(),
                                  aspectRatio: aspectRatio,
                                  elements: widget.templateModelA!
                                      .toBoardElements(
                                          scale:
                                              previewWidth / (Get.size.width),
                                          maxHeight: previewHeight),
                                  canvasSize: Size(previewWidth, previewHeight),
                                  onElementSelected: (_) {},
                                  onElementPositionChanged: (_, __) {},
                                  editable: false,
                                  textContents: previewTextsA,
                                ),
                              ),
                            ),

                          SizedBox(width: 16.w),

                          // B面预览 - 仅在不是相同面板时显示
                          if (!isSameSides &&
                              widget.sampleValue != 2 &&
                              widget.templateModelB != null)
                            Expanded(
                              child: Container(
                                width: previewWidth,
                                height: previewHeight,
                                child: BoardWidget(
                                  boardKey: GlobalKey(),
                                  aspectRatio: aspectRatio,
                                  elements: widget.templateModelB!
                                      .toBoardElements(
                                          scale: previewWidth / Get.size.width,
                                          maxHeight: previewHeight),
                                  canvasSize: Size(previewWidth, previewHeight),
                                  onElementSelected: (_) {},
                                  onElementPositionChanged: (_, __) {},
                                  editable: false,
                                  textContents: previewTextsB,
                                ),
                              ),
                            ),
                        ],
                      );
                    },
                  ),
                  10.verticalSpace,
                ],
              ),
            ),
          Padding(
            padding: EdgeInsets.symmetric(vertical: 8.w, horizontal: 16.w),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Spacer(),
                GestureDetector(
                  onTap: () {
                    if (tabIndex == 1) {
                      addNewField('B');
                    } else {
                      addNewField('A');
                    }
                  },
                  child: Row(
                    children: [
                      Image.asset(
                        'assets/images/Frame@2x (11).png',
                        width: 14.w,
                        height: 14.w,
                      ),
                      4.horizontalSpace,
                      Text(
                        AppLocalizations.of(context)!.translate('add_new_info'),
                        style: TextStyle(
                          fontSize: 14,
                          fontWeight: FontWeight.normal,
                          letterSpacing: 0,
                          color: Color.fromRGBO(51, 51, 51, 1),
                        ),
                      ),
                    ],
                  ),
                )
              ],
            ),
          ),
          Expanded(
            child: SingleChildScrollView(
              controller: _scrollController,
              child: Column(
                children: [
                  if (widget.templateModelA != null ||
                      widget.templateModelB != null)
                    Padding(
                      padding: EdgeInsets.symmetric(
                          horizontal: 16.w, vertical: 12.w),
                      child: Column(
                        children: [
                          // 成员信息输入部分
                          if (isSameSides && memberInfoListA.isNotEmpty)
                            _buildASideInputs()
                          else ...[
                            if (memberInfoListA.isNotEmpty && tabIndex == 0)
                              _buildASideInputs(),
                            if (memberInfoListB.isNotEmpty && tabIndex == 1)
                              _buildBSideInputs(),
                          ],
                          12.verticalSpace,
                        ],
                      ),
                    ),
                  if (widget.templateModelA == null &&
                      widget.templateModelB == null)
                    Padding(
                      padding: EdgeInsets.symmetric(
                          horizontal: 16.w, vertical: 12.w),
                      child: Column(
                        children: [
                          // 成员信息输入部分
                          _buildASideInputs(),
                          12.verticalSpace,
                        ],
                      ),
                    )
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    controllers.forEach((_, controller) => controller.dispose());
    super.dispose();
  }
}
